package cn.ll.action;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import cn.ll.ModelAndView.ExcelView;
import cn.ll.po.Customer;
import cn.ll.po.Department;
import cn.ll.po.Permissions;
import cn.ll.po.User;
import cn.ll.service.ContractService;
import cn.ll.service.CustomerService;
import cn.ll.service.TaskService;
import cn.ll.util.SystermUtil;
import cn.ll.vo.LoginUser;

public class CustomerAction extends Action {

	CustomerService customerService = null;

	public ModelAndView readExcel(HttpServletRequest request, HttpServletResponse response) {

		logger.debug("read");
		String id = request.getParameter("id");
		Map condition = new HashMap();
		if (id != null) {
			condition.put("id", id);
		}

		List<Permissions> curplist = (List<Permissions>) request.getSession().getAttribute("CURRENT_PERMISSIONS");
		String permission = "customermgr";
		String action = "exp";
		List<Permissions> readplist = SystermUtil.usrPermissionsList(permission, action, curplist);

		Map map = customerService.read(condition, readplist);
		List list = (List) map.get("list");
		Integer totalcount = (Integer) map.get("totalcount");
		Map rs = new HashMap();
		rs.put("success", true);
		rs.put("items", list);
		rs.put("totalcount", totalcount);

		ExcelView excelView = new ExcelView();
		return new ModelAndView(excelView, "items", list);

	}

	public void read(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {

		logger.debug("read");
		String id = request.getParameter("id");
		String startline = request.getParameter("start");
		String num = request.getParameter("limit");
		String readtype = request.getParameter("readtype");

		if (id == null && (readtype == null || readtype.length() == 0)) {

			Map rs = new HashMap();
			rs.put("success", false);
			rtn(rs, request, response);
			return;
		}

		Map condition = new HashMap();
		if (id != null) {
			condition.put("id", id);
		}
		if (startline != null) {
			condition.put("startline", Integer.parseInt(startline));
		}
		if (num != null) {
			condition.put("num", Integer.parseInt(num));
		}
		condition.put("readtype", readtype);

		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");
		if (loginUser != null) {
			condition.put("uid", loginUser.getUser().getId());
		}
		// 获取当前登录用户的权限列表
		List<Permissions> curplist = (List<Permissions>) request.getSession().getAttribute("CURRENT_PERMISSIONS");
		// String permission = "customermgr";
		// String action = "read";
		// //获取当前用户的用户管理权限的read的权限
		// List<Permissions> readplist =
		// SystermUtil.usrPermissionsList(permission, action, curplist);

		Map map = customerService.read(condition, curplist);
		List list = (List) map.get("list");
		Integer totalcount = (Integer) map.get("totalcount");
		list = this.tranToMapList(list);
		

		Map rs = new HashMap();
		rs.put("success", true);
		rs.put("items", list);
		rs.put("totalcount", totalcount);
		rtn(rs, request, response);

	}

	/**
	 * 将用户的信息转化为map列表
	 * 
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	private List tranToMapList(List ls) throws IllegalAccessException, InvocationTargetException,
			NoSuchMethodException {

		List lsMap = new ArrayList();
		for (int i = 0; i < ls.size(); i++) {
			Customer item = (Customer) ls.get(i);
			Map mp = new HashMap();
			mp = BeanUtils.describe(item);
			if (item.getStatus() == 0) {
				mp.put("statusStr", "已保存");
			} else if (item.getStatus() == 1) {
				mp.put("statusStr", "已提交");
			} else if (item.getStatus() == 2) {
				mp.put("statusStr", "已通过");
			} else if (item.getStatus() == 4) {
				mp.put("statusStr", "被打回");
			}
			lsMap.add(mp);

		}

		return lsMap;
	}

	/**
	 * 根据状态获得用户列表
	 * 
	 * @param request
	 * @param response
	 */
	public void getCusByStatus(HttpServletRequest request, HttpServletResponse response) {
		String status = request.getParameter("status");
		String limit = request.getParameter("limit");
		String start = request.getParameter("start");
		if(limit == null || limit.length() > 0){
			limit = "10";
		}
		if(start == null || start.length() > 0){
			start = "1";
		}
		List<Customer> list = null;
		Integer count = 0;
		if (status != null && status.length() > 0) {
			//获得当前登录用户的权限列表
			List<Permissions> curplist = (List<Permissions>) request.getSession().getAttribute("CURRENT_PERMISSIONS");
			//客户审核的权限
			List<Permissions> rp = SystermUtil.usrPermissionsList("customeraudit", "read", curplist);
			if(rp.size() > 0){
				Map map = customerService.findByStatus(Integer.parseInt(status),Integer.parseInt(start),Integer.parseInt(limit));
				list = (List<Customer>) map.get("list");
				count = (Integer) map.get("totalcount");
			}
		}
		Map rs = new HashMap();
		if(list != null){
			rs.put("success", true);
			rs.put("items", list);
		}
		else{
			rs.put("success", false);
		}
		rs.put("totalcount", count);
		rtn(rs, request, response);
	}

	/**
	 * 更新客户记录的状态.0:待审核,1:审核通过;2审核不通过
	 * 
	 * @param request
	 * @param response
	 */
	public void updateCusStatus(HttpServletRequest request, HttpServletResponse response) {
		String task_status_str = request.getParameter("itemlist");
		JSONArray jsa = JSONArray.fromObject(task_status_str);
		if (jsa != null) {
			int len = jsa.size();
			for (int i = 0; i < len; i++) {
				JSONObject jso = jsa.getJSONObject(i);
				String cusid = jso.getString("id");
				int status = jso.getInt("status");

				Customer customer = customerService.findById(cusid);
				if (customer != null) {
					customer.setStatus(status);
					customerService.update(customer);
				}
			}
			Map rs = new HashMap();
			rs.put("success", true);
			rtn(rs, request, response);
		} else {
			Map rs = new HashMap();
			rs.put("success", false);
			rtn(rs, request, response);
		}
	}

	public void create(HttpServletRequest request, HttpServletResponse response) throws IllegalAccessException,
			InvocationTargetException {

		Customer customer = this.getCustomerFromPara(request);
		LoginUser loginUser = (LoginUser) request.getSession().getAttribute("CURRENT_USER");
		Department department = (Department)request.getSession().getAttribute("CURRENT_DEPARTMENT");
		if(loginUser != null && loginUser.getUser() != null){
			customer.setUserid(loginUser.getUser().getId());
			customer.setUsername(loginUser.getUser().getUsername());
		}
		Map suc = customerService.create(customer, loginUser);

		rtn(suc, request, response);

	}

	private Customer getCustomerFromPara(HttpServletRequest request) throws IllegalAccessException,
			InvocationTargetException {

		String[] properties = { "id", "customername", "tel", "address", "contactorname", "subdepartment",
				"continent", "country", "city", "comtype", "fax", "website", "contactgender", "contactoremail",
				"contactorposition", "contacttel", "contactmobile", "comstyle", "remarks", "status"};

		Customer customer = new Customer();

		for (int i = 0; i < properties.length; i++) {
			String para = request.getParameter(properties[i]);
			if (para != null && !para.equals("")) {
				BeanUtils.setProperty(customer, properties[i], para);
			}
		}

		return customer;
	}

	public void delete(HttpServletRequest request, HttpServletResponse response) {

		String idListStr = request.getParameter("idList");

		JSONArray jArray = JSONArray.fromObject(idListStr);

		Object[] idList = jArray.toArray();

		List customerList = new ArrayList<Customer>();
		for (int i = 0; i < idList.length; i++) {
			Customer customer = new Customer();
			customer.setId((String) idList[i]);
			customerList.add(customer);
		}

		Map suc = customerService.delete(customerList);

		rtn(suc, request, response);

	}

	/**
	 * 返回客户的Id和名称
	 * 
	 * @param request
	 * @param response
	 */
	public void namelist(HttpServletRequest request, HttpServletResponse response) {
		List list = customerService.namelist();
		Map map_send = new java.util.HashMap(0);
		map_send.put("items", list);
		rtn(map_send, request, response);
		return;
	}

	public void fuzzyQuery(HttpServletRequest request, HttpServletResponse response) {

		String condition_str = request.getParameter("cdt");
		JSONObject jso = JSONObject.fromObject(condition_str);

		String customername = jso.getString("customername");
		String subdepartment = jso.getString("subdepartment");
		String tel = jso.getString("tel");
		String address = jso.getString("address");

		Map map = new HashMap(0);
		if (customername != null && customername.length() > 0)
			map.put("customername", customername);
		if (subdepartment != null && subdepartment.length() > 0)
			map.put("subdepartment", subdepartment);
		if (tel != null && tel.length() > 0)
			map.put("tel", tel);
		if (address != null && address.length() > 0)
			map.put("address", address);
		if (map.size() > 0) {
			List<Customer> list = customerService.fuzzyQuery(map);

			Map map_send = new java.util.HashMap(0);
			map_send.put("items", list);
			map_send.put("success", true);
			rtn(map_send, request, response);
			return;
		} else {
			Map map_send = new java.util.HashMap(0);
			map_send.put("success", false);
			rtn(map_send, request, response);
			return;
		}
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

}
